package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.AssociateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AssociateServiceImpl implements AssociateService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult search(UserSearchDto dto) {
        //1.校验
        if (dto==null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getPageSize()<0 || dto.getPageSize()>100){
            dto.setPageSize(10);
        }

        //2.基于mongodb做 模糊查询  正则表达式
        //类似sql   select * from ap_associate_words where associateWords like '%  dto.getSearchWords()  %'
        Query query = Query.query(Criteria.where("associateWords").regex(".*?\\" + dto.getSearchWords() + ".*"));
        List<ApAssociateWords> list = mongoTemplate.find(query, ApAssociateWords.class);

        //3.封装结果返回
        return ResponseResult.okResult(list);
    }
}
